﻿/*
 * class MysqlConn 
 * MYSQL数据库操作类
 * */
package cn.nkjobsearch.mysql;

import cn.nkjobsearch.Config.Config;

import java.sql.*;

public class MysqlConn {
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;

	void init() {
		try {
			Class.forName(Config.MYSQL_sDBDriver);
			conn = DriverManager.getConnection(Config.MYSQL_sConnStr,
					Config.MYSQL_user, Config.MYSQL_password);
			stmt = conn.createStatement();
		} catch (Exception e) {
			if (Config.DEBUG_ERROR) {
				e.printStackTrace();
			}
		}
	}

	public MysqlConn() {
		init();
	}

	public boolean executeInsert(String sql) {
		try {
			if (stmt != null) {
				stmt.execute(sql);
			}
		} catch (SQLException e) {
			if (Config.DEBUG_INFO) { 
				if(e.getErrorCode() != 1062) {//重复插入
					System.out.println(sql);
				}
			}
			if (Config.DEBUG_ERROR) {
				if(e.getErrorCode() != 1062) {//重复插入
					e.printStackTrace();
				}
			} 
			return false;
		}
		return true;
	}

	public boolean executeUpdate(String sql) {
		try {
			if (stmt != null) {
				stmt.executeUpdate(sql);
			}
		} catch (SQLException e) {
			if (Config.DEBUG_INFO) {
				System.out.println(sql);
			}
			if (Config.DEBUG_ERROR) {
				e.printStackTrace();
			}
			return false;
		}
		return true;
	}

	public ResultSet executeQuery(String sql) {
		try {
			if (stmt != null) {
				rs = stmt.executeQuery(sql);
			}
		} catch (Exception e) {
			if (Config.DEBUG_INFO) {
				System.out.println(sql);
			}
			if (Config.DEBUG_ERROR) {
				e.printStackTrace();
			}
			return null;
		}
		return rs;
	}

	public boolean executeDelete(String sql) {
		try {
			if (stmt != null) {
				stmt.executeUpdate(sql);
			}
		} catch (Exception e) {
			if (Config.DEBUG_INFO) {
				System.out.println(sql);
			}
			if (Config.DEBUG_ERROR) {
				e.printStackTrace();
			}
			return false;
		}
		return true;
	}

	public boolean close() {
		try {
			if (conn != null) {
				conn.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (rs != null) {
				rs.close();
			}
		} catch (Exception e) {
			if (Config.DEBUG_ERROR) {
				e.printStackTrace();
			}
			return false;
		}
		return true;
	}
}
